package cn.itcast.wanxinp2p.consumer.service.Impl;

import cn.itcast.wanxinp2p.api.account.model.AccountDTO;
import cn.itcast.wanxinp2p.api.account.model.AccountRegisterDTO;
import cn.itcast.wanxinp2p.api.account.model.ConsumerRegisterDTO;

import cn.itcast.wanxinp2p.common.domain.CodePrefixCode;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.exception.BusinessException;
import cn.itcast.wanxinp2p.consumer.agent.AccountApiAgent;
import cn.itcast.wanxinp2p.consumer.common.CodeNoUtil;
import cn.itcast.wanxinp2p.consumer.common.ConsumerErrorCode;
import cn.itcast.wanxinp2p.consumer.entity.Consumer;
import cn.itcast.wanxinp2p.consumer.mapper.ConsumerMapper;
import cn.itcast.wanxinp2p.consumer.service.ConsumerService;

import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.Hmily;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class ConsumerServiceImpl implements ConsumerService {
   @Autowired
    private ConsumerMapper consumerMapper;
   @Autowired
    private AccountApiAgent accountApiAgent;
    @Override
    public Integer checkMobile(String mobile) {
        //根据手机号查询用户，存在返回1 不存在返回0
        Integer bymobile=consumerMapper.bymobile(mobile);
        if (bymobile!=null){
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    @Hmily(confirmMethod = "confirmRegister", cancelMethod = "cancelRegister")
    public void register(ConsumerRegisterDTO consumerRegisterDTO) {
        log.info("execute tryRegister");
        Consumer consumer = new Consumer();
        //1、检测是否已注册，如果已经注册，则抛出 ConsumerErrorCode.E_140107 异常

        String mobile = consumerRegisterDTO.getMobile();
        Integer bymobile = consumerMapper.bymobile(mobile);

        if (bymobile == 1) {
          throw   new BusinessException(ConsumerErrorCode.E_140107);
        }
        BeanUtils.copyProperties(consumerRegisterDTO, consumer);
        consumer.setUsername(CodeNoUtil.getNo(CodePrefixCode.CODE_NO_PREFIX));
        consumer.setUserNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX));
        consumer.setIsBindCard(0);

        //2、如果用户没有注册，则保存该用户数据 到 consumer 表中
        Integer save = consumerMapper.save(consumer);

        //3、并通过Feign远程调用 统一账号服务 实现 账号的保存
        AccountRegisterDTO accountRegisterDTO = new AccountRegisterDTO();
        BeanUtils.copyProperties(consumer, accountRegisterDTO);
        accountApiAgent.register(accountRegisterDTO);
    }

    //confirm
    public void confirmRegister(ConsumerRegisterDTO consumerRegisterDTO) {
        log.info("execute confirmRegister");

    }

    //cancle
    public void cancelRegister(ConsumerRegisterDTO consumerRegisterDTO) {
        log.info("execute cancelRegister");
        //TODO 删除用户
        consumerMapper.deleteByMobile(consumerRegisterDTO.getMobile());
    }

}
